<template>
  <div style="margin-top: 20px;width: 360px">
    <el-upload class="upload-css" :file-list="uploadFiles" ref="upload" drag :on-success="upLoadSuccess"
               :before-upload="beforeUpload" :on-error="upLoadError" :action="uploadURL" :auto-upload="false" :on-remove="handleRemove"
               :before-remove="beforeRemove" :limit="this.limit">
      <i class="el-icon-upload"></i>
      <div class="el-upload__text">
        {{ this.msg }}<br>
        将文件拖到此处，或<em>点击上传</em><br>
      </div>
<!--      <div class="el-upload__tip" slot="tip">-->
<!--        上传招标文件，且不超过28M-->
<!--      </div>-->
    </el-upload>
    <el-button style="margin-top:10px;margin-left: 120px;width: 100px" size="small" type="success" @click="submitUpload">点击上传</el-button>
  </div>
</template>

<script>
export default {
  name: 'FileUpload',
  props: ["projectId","type","limit","msg"],
  data() {
    return {
      projectName: "",
      //uploadURL: "/project/upload?a=1",
      uploadFiles: [] //上传的文件列表
    };
  },
  computed: {
    //文件的上传路径
    //附带用户id和项目名称
    uploadURL: function () {
      //var userId = this.$store.state.userId;
      return "http://localhost:8088/api/upload?id="+this.$store.getters.getUser.id+"&projectId="+this.projectId+"&type="+this.type;
    }
  },
  methods: {
    //文件上传
    submitUpload() {
      this.$refs.upload.submit()
    },
    //文件上传成功时的钩子
    upLoadSuccess(response) {
      if (response.code === 200) {
        this.$emit('uploadResponse', response);
      } else {
        this.$message.error("文件上传失败")
      }
    },
    beforeUpload(file) {
        // 拿到文件后缀名
        const fileType = file.name.substring(file.name.lastIndexOf('.') + 1)
        // 当然拉我的需求是只需要图片和pdf，大家有需要可以在此处扩展
        const isDoc = fileType === 'doc'
        const isDocx = fileType === 'docx'
        const isPdf = fileType === 'pdf'
        // const isLt1M = file.size / 1024 / 1024 < 1;
        // 根据后缀名判断文件类型
        if (!isDoc && !isDocx && !isPdf) {
          this.$message.error('只能上传doc和pdf格式的文件！')
          return false
        }
        // 可以限制图片的大小
        // if (!isLt1M) {
        //     this.$message.error('上传图片大小不能超过 1MB!');
        // }
        return isDoc || isDocx || isPdf
      },
    //文件上传失败时的钩子
    upLoadError(response) {
      console.log(response);
    },
    beforeRemove(file) {
      return this.$confirm(`确定移除 ${ file.name }？`);
    },
    handleRemove(file) {
      this.$axios.get("/delete?file_name="+file.response.data).then(res => {
        this.$emit('deleteResponse', res.data.code);
      });
      this.$message.success("文件删除成功")
    }
  }
};

</script>

<style lang="scss" scoped>
</style>

